package com.zondy.mapgis.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.tools.zip.ZipFile;




/**
 * 文件操作类
 * @author fjl
 *
 */
public class FileOperation
{
	private static final String TAG = FileOperation.class.getSimpleName();
	public File file;

	public FileOperation(File file)
	{
		this.file = file;
	}

	public boolean FileContainStr(String inputString)
	{
		ArrayList<String> fileStrArrayList = new ArrayList<String>();
		String[] readString = readFrFile().split("\r\n");
		for (int i = 0; i < readString.length; i++)
		{
			fileStrArrayList.add(readString[i]);
			if (fileStrArrayList.contains(inputString))
			{
				return true;
			}
		}
		return false;
	}

	public String readFrFile()
	{
		try
		{
			byte[] buff = new byte[256];
			FileInputStream fis = new FileInputStream(file);
			int len = fis.read(buff);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			outputStream.write(buff, 0, len);
			return new String(outputStream.toByteArray());

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	// 追加到文件尾
	public void write2file(String string)
	{
		String context = string + "\r\n";
		try
		{
			FileOutputStream fOutputStream = new FileOutputStream(file, true);// 设置为true，可以追加
			fOutputStream.write(context.getBytes());
			fOutputStream.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public void clearFile(String string)
	{
		String context = string + "\r\n";
		try
		{
			FileOutputStream fos = new FileOutputStream(file, false);
			fos.write(context.getBytes());
			fos.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 读文件的得到文件字节流
	 * 
	 * @param filePath
	 * @return
	 */
	public static byte[] readFileToBytes(String filePath)
	{
		byte[] bytes = null;
		try
		{
			BufferedInputStream bi = new BufferedInputStream(new FileInputStream(filePath));
			// 输入流转字节流
			bytes = new byte[bi.available()];
			bi.read(bytes);
			bi.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return bytes;

	}

	/**
	 * 把字节流放到本地
	 * 
	 * @param bytes
	 * @param filePath
	 * @throws IOException
	 */
	public static void writeBytesFile(byte[] bytes, String filePath) throws IOException
	{
		try
		{
			File Fout = new File(filePath);
			if (!Fout.exists())
			{
				(new File(Fout.getParent())).mkdirs();
			}
			BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(filePath));
			bo.write(bytes);
			bo.flush();
			bo.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 文件输入流写入到本地
	 * 
	 * @param in
	 * @param filePath
	 */
	public static void writeInputStreamFile(InputStream in, String filePath)
	{
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		BufferedOutputStream bo;
		byte[] buffer = new byte[1024];
		int ch;
		try
		{
			while ((ch = in.read(buffer)) != -1)
			{
				bytestream.write(buffer, 0, ch);
			}
			byte[] data = bytestream.toByteArray();

			// 判断父文件夹是否被创建
			File Fout = new File(filePath);
			if (!Fout.exists())
			{
				(new File(Fout.getParent())).mkdirs();
			}

			bo = new BufferedOutputStream(new FileOutputStream(filePath));
			bo.write(data);
			bo.flush();
			bo.close();
			bytestream.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 读文件的得到文件字节流
	 * 
	 * @param filePath
	 * @return
	 */
	public static void writeInFile(InputStream in, String filePath)
	{
		byte[] bytes = null;

		try
		{
			BufferedInputStream bi = new BufferedInputStream(in);
			// 输入流转字节流
			bytes = new byte[bi.available()];
			bi.read(bytes);
			bi.close();

			BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(filePath));
			bo.write(bytes);
			bo.flush();
			bo.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	/**
	 * 删除文件，可以是文件或文件夹
	 * 
	 * @param filePath(要删除的文件名)
	 * @return 删除成功返回true，否则返回false
	 */
	public static boolean delteFile(String filePath)
	{
		File file = new File(filePath);
		if (!file.exists())
		{
			System.out.println("删除文件失败:" + filePath + "不存在！");
			return false;
		}
		else
		{
			if (file.isFile())
			{
				return file.delete();
			}
			else
			{
				return false;
//				return deleteDirectory(filePath);
			}
		}

	}

	/**
	 * 读输入流得到文件字节流
	 * 
	 * @param filePath
	 * @return
	 */
	public static byte[] readInputStreamToBytes(InputStream in)
	{
		byte[] bytes = null;
		try
		{
			BufferedInputStream bi = new BufferedInputStream(in);
			// 输入流转字节流
			bytes = new byte[bi.available()];
			bi.read(bytes);
			bi.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return bytes;

	}

	/**
	 * 输入流转字节流
	 * */
	public static byte[] InputStreamToByte(InputStream is) throws IOException
	{
		ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int ch;
		while ((ch = is.read(buffer)) != -1)
		{
			bytestream.write(buffer, 0, ch);
		}
		byte data[] = bytestream.toByteArray();
		bytestream.close();
		return data;

	}

	/**
	 * 文件按日期排序
	 * 
	 * @param flieLst 文件列表
	 * @return
	 */
	public static List<File> orderByDate(List<File> flieLst)
	{
		List<File> orderFileLst = new ArrayList<File>();
		File[] fs = new File[flieLst.size()];
		flieLst.toArray(fs);
		Arrays.sort(fs, new Comparator<File>()
		{
			public int compare(File f1, File f2)
			{
				long diff = f1.lastModified() - f2.lastModified();
				if (diff > 0)
					return 1;
				else if (diff == 0)
					return 0;
				else
					return -1;
			}

			public boolean equals(Object obj)
			{
				return true;
			}

		});
		for (int i = fs.length - 1; i > -1; i--)
		{
			// System.out.println(fs[i].getName());
			// System.out.println(new Date(fs[i].lastModified()));
			orderFileLst.add(fs[i]);
		}
		return orderFileLst;
	}


	/**
	 * 解压ZIP文件
	 * 
	 * @param zipFileName ZIP文件
	 * @param outputDirectory 解压目的存放路径
	 */
	public static void unzip(InputStream zipFileName, String outputDirectory)
	{
		try
		{
			BufferedOutputStream dest = null;
			ZipInputStream in = new ZipInputStream(zipFileName);
			// 获取ZipInputStream中的ZipEntry条目，一个zip文件中可能包含多个ZipEntry，
			// 当getNextEntry方法的返回值为null，则代表ZipInputStream中没有下一个ZipEntry，
			// 输入流读取完成；
			ZipEntry entry = in.getNextEntry();
			while (entry != null)
			{
				// 创建以zip包文件名为目录名的根目录
				File file = new File(outputDirectory);
				file.mkdir();
				if (entry.isDirectory())
				{
					String name = entry.getName();
					name = name.substring(0, name.length() - 1);

					file = new File(outputDirectory + File.separator + name);
					file.mkdir();

				}
				else
				{
					// 判断父文件夹是否被创建
					File Fout = new File(outputDirectory, entry.getName());
					if (!Fout.exists())
					{
						(new File(Fout.getParent())).mkdirs();
					}
					int count;
					byte data[] = new byte[2048];
					file = new File(outputDirectory + File.separator + entry.getName());
					file.createNewFile();
					FileOutputStream out = new FileOutputStream(file);
					dest = new BufferedOutputStream(out, 2048);
					while ((count = in.read(data, 0, 2048)) != -1)
					{
						dest.write(data, 0, count);
					}
					dest.flush();
					dest.close();
				}
				// 读取下一个ZipEntry
				entry = in.getNextEntry();
			}
			in.close();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 解压(处理中文文件名乱码的问题)
	 * 
	 * @param zipFileName
	 * @param extPlace
	 * @return
	 * @throws Exception
	 */
	public static boolean unZipFiles(String zipFileName, String extPlace)
	{
		try
		{
			(new File(extPlace)).mkdirs();
			File f = new File(zipFileName);
			ZipFile zipFile = new ZipFile(zipFileName, "GBK"); // 处理中文文件名乱码的问题
			if ((!f.exists()) && (f.length() <= 0))
			{
				throw new Exception("要解压的文件不存在!");
			}
			String strPath, gbkPath, strtemp;
			File tempFile = new File(extPlace);
			strPath = tempFile.getAbsolutePath();
			Enumeration<?> e = zipFile.getEntries();
			while (e.hasMoreElements())
			{
				ZipEntry zipEnt = (ZipEntry) e.nextElement();
				gbkPath = zipEnt.getName();
				if (zipEnt.isDirectory())
				{
					strtemp = strPath + File.separator + gbkPath;
					File dir = new File(strtemp);
					dir.mkdirs();
					continue;
				}
				else
				{
					// 读写文件
					InputStream is = zipFile.getInputStream((org.apache.tools.zip.ZipEntry) zipEnt);
					BufferedInputStream bis = new BufferedInputStream(is);
					gbkPath = zipEnt.getName();
					strtemp = strPath + File.separator + gbkPath;

					// 建目录
					String strsubdir = gbkPath;
					for (int i = 0; i < strsubdir.length(); i++)
					{
						if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/"))
						{
							String temp = strPath + File.separator + strsubdir.substring(0, i);
							File subdir = new File(temp);
							if (!subdir.exists())
								subdir.mkdir();
						}
					}
					FileOutputStream fos = new FileOutputStream(strtemp);
					BufferedOutputStream bos = new BufferedOutputStream(fos);
					int c;
					while ((c = bis.read()) != -1)
					{
						bos.write((byte) c);
					}
					bos.close();
					fos.close();
				}
			}
			return true;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 获取当前文件夹下所有文件（针对MapGIS Collector）
	 * 
	 * @param rootFile
	 * @return
	 */
	public static List<File> getLocalMapFile(File rootFile)
	{
		// 当前路径下所有文件
		List<File> allFiles = new ArrayList<File>();

		File[] mRootFiles = rootFile.listFiles();
		// 根目录
		for (int i = 0; i < mRootFiles.length; i++)
		{
			if (mRootFiles[i].isFile())
			{
				allFiles.add(mRootFiles[i]);
			}
			else
			{
				if(mRootFiles[i].getName().equalsIgnoreCase("Download"))
				{
					continue;
				}
				//过滤本地在线地图
				if (mRootFiles[i].getName().equalsIgnoreCase("") == false)
				{
					// 二级目录
					File[] secondFiles = mRootFiles[i].listFiles();
					for (int j = 0; j < secondFiles.length; j++)
					{
						if (secondFiles[j].isFile())
						{
							allFiles.add(secondFiles[j]);
						}
						else
						{
							// 三级目录
							File[] thirdFiles = secondFiles[j].listFiles();
							for (int x = 0; x < thirdFiles.length; x++)
							{
								if (thirdFiles[x].isFile())
								{
									allFiles.add(thirdFiles[x]);
								}
							}
						}
					}

				}
			}
		}
		return allFiles;
	}
	
	/**
	 * 获取当前文件夹下所有文件（针对MapGIS Collector）
	 * 
	 * @param rootFile
	 * @return
	 */
	public static List<File> getAllFile(File rootFile)
	{
		// 当前路径下所有文件
		List<File> allFiles = new ArrayList<File>();

		File[] mRootFiles = rootFile.listFiles();
		// 根目录
		for (int i = 0; i < mRootFiles.length; i++)
		{
			if (mRootFiles[i].isFile())
			{
				allFiles.add(mRootFiles[i]);
			}
			else
			{
				//过滤本地在线地图
				if (mRootFiles[i].getName().equalsIgnoreCase("") == false)
				{
					// 二级目录
					File[] secondFiles = mRootFiles[i].listFiles();
					for (int j = 0; j < secondFiles.length; j++)
					{
						if (secondFiles[j].isFile())
						{
							allFiles.add(secondFiles[j]);
						}
						else
						{
							// 三级目录
							File[] thirdFiles = secondFiles[j].listFiles();
							for (int x = 0; x < thirdFiles.length; x++)
							{
								if (thirdFiles[x].isFile())
								{
									allFiles.add(thirdFiles[x]);
								}
							}
						}
					}

				}
			}
		}
		return allFiles;
	}


		

	/**
	 * 打印文件
	 * 
	 * @param fileLst
	 */
	public static void printLst(List<File> fileLst)
	{
		System.out.println("******************");
		for (File file : fileLst)
		{
			System.out.println(file.getName());
			System.out.println(new Date(file.lastModified()));
		}
		System.out.println("================");
	}
}
